/*
 * Copyright (c) 2022 HiSilicon (Shanghai) Technologies CO., LIMITED.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <stdio.h>
#include <string.h>
#include <unistd.h>

#include "iot_errno.h"
#include "ohos_init.h"
#include "cmsis_os2.h"
#include "iot_gpio.h"
#include "iot_gpio_ex.h"
#include "iot_uart.h"

extern uint8_t type;
extern float temperature;
extern float ph;
extern float hum;

static const char *data = "Hello, HI3861_WIFIIOT!\r\n";
static const char *init_buff = "Uart1 Init OK!\r\n";
static const char pur_cmd[] = {0x01, 0x03, 0x00, 0x12, 0x00, 0x02, 0x64, 0x0E};
static const char ph_cmd[]  = {0x01, 0x03, 0x00, 0x06, 0x00, 0x01, 0x64, 0x0B};

uint8_t uart1_uart2_flag = 0;

#define IOT_UART_IDX_1 1                                

#define UART_BUFF_SIZE 1000
#define RS485_BUFF_SIZE 9

#define PH_READ_STATE          0
#define PUR_READ_STATE         1
#define FLOWER_TYPE_RESD_STATE 2

 
/* 返回ch字符在sign数组中的序号 */
int getIndexOfSigns(char ch)
{
    if(ch >= '0' && ch <= '9')
    {
        return ch - '0';
    }
    if(ch >= 'A' && ch <='F') 
    {
        return ch - 'A' + 10;
    }
    if(ch >= 'a' && ch <= 'f')
    {
        return ch - 'a' + 10;
    }
    return -1;
}

/* 十六进制数转换为十进制数 */
long hexToDec(char *source)
{
    long sum = 0;
    long t = 1;
    int i, len;
 
    len = strlen(source);
    for(i=len-1; i>=0; i--)
    {
        sum += t * getIndexOfSigns(*(source + i));
        t *= 16;
    }  
 
    return sum;
}

void HexToAscii(uint8_t *src, char *dest, int len)
{
    char dh,dl;  //字符串的高位和低位
    int i;
    if(src == NULL || dest == NULL)
    {
        return;
    }
    if(len < 1)
    {
        return;
    }
    for(i = 0; i < len; i++)
    {
        dh = '0' + src[i] / 16;
        dl = '0' + src[i] % 16;
        if(dh > '9')
        {
            dh = dh - '9' - 1 + 'A'; // 或者 dh= dh+ 7;
        }
        if(dl > '9')
        {
            dl = dl - '9' - 1 + 'A'; // 或者dl = dl + 7;
        }
        dest[2*i] = dh;
        dest[2*i+1] = dl;
    }
     dest[2*i] = '\0';
}

/*   使用串口线连接 外设拓展板 P7   */
static void Uart1Task(const char *arg)
{
    uint8_t uart_buff[UART_BUFF_SIZE] = {0};
    uint8_t *uart_buff_ptr = uart_buff;
    uint8_t flower_type = 0;
    uint8_t state = 0;
    uint8_t datas[50];
    uint8_t data_hum[2];
    uint8_t data_temp[2];
    uint8_t data_ph[2];
    uint32_t ret;   

    IoTGpioInit(IOT_IO_NAME_GPIO_0);                                //初始化 GPIO0
    IoSetFunc(IOT_IO_NAME_GPIO_0, IOT_IO_FUNC_GPIO_0_UART1_TXD);    // gpio0复用Uart1_TXD
    IoTGpioInit(IOT_IO_NAME_GPIO_1);                                //初始化 GPIO1
    IoSetFunc(IOT_IO_NAME_GPIO_1, IOT_IO_FUNC_GPIO_1_UART1_RXD);    // gpio1复用Uart1_RXD

    IotUartAttribute uart_attr1 = {
        .baudRate = 9600,                                         //设置波特率为      115200
        .dataBits = IOT_UART_DATA_BIT_8,                            //设置数据位为      8位
        .stopBits = IOT_UART_STOP_BIT_1,                            //设置停止位为      1位
        .parity = IOT_UART_PARITY_NONE,                             //设置校验为为      无
    };

    ret = IoTUartInit(IOT_UART_IDX_1,&uart_attr1);                    //初始化 Uart1
    if(ret != IOT_SUCCESS)
    {
        printf("Failed to init uart1!\r\n");
    }
    else
    {
        printf("Uart1 init success\r\n");
    }
    IoTUartWrite(IOT_UART_IDX_1,(uint8_t*)init_buff,strlen(init_buff));
    while(1)
    {
//        printf("state = %d\r\n",state);
        switch (state)
        {
            case PH_READ_STATE:
                memset(uart_buff,0,sizeof(uart_buff));
                IoTUartWrite(IOT_UART_IDX_1,(uint8_t*)ph_cmd,8);
                IoTUartRead(IOT_UART_IDX_1,uart_buff,9);
                if(uart_buff[0] == 0xaa && uart_buff[1] == 0x55)        //花卉种类
                {
                    datas[0]=uart_buff[3];
                    datas[1]=uart_buff[4];
//                    temp = hexToDec(datas);
                    datas[0]=uart_buff[5];
                    datas[1]=uart_buff[6];    
//                    hum =  hexToDec(datas);              
                }
                state = PUR_READ_STATE;
                break;
            case PUR_READ_STATE:
                memset(uart_buff,0,sizeof(uart_buff));
                IoTUartWrite(IOT_UART_IDX_1,(uint8_t*)pur_cmd,8);
                IoTUartRead(IOT_UART_IDX_1,uart_buff_ptr,7);
                if(uart_buff[0] == 0xaa && uart_buff[1] == 0x55)        //花卉种类
                {
                    datas[0]=uart_buff[3];
                    datas[1]=uart_buff[4];
//                    ph = hexToDec(datas);            
                }
                state = FLOWER_TYPE_RESD_STATE;
                break;
            case FLOWER_TYPE_RESD_STATE:
                state = PH_READ_STATE;
                break;
            default:
                state = PH_READ_STATE;
                break;
        }
        
/*
        uart1_uart2_flag = 1;
        IoTUartRead(IOT_UART_IDX_1, uart_buff_ptr,10);
        IoTUartWrite(IOT_UART_IDX_1,uart_buff_ptr,10);
        for(int i = 0;i<10;i++)
        {
            printf("uart_buff_ptr[%d] = %x\r\n",i,uart_buff_ptr[i]);
        }
        uart1_uart2_flag = 0;
        */
        IoTUartRead(IOT_UART_IDX_1, uart_buff_ptr,9);             //串口1 接受
        for(int i = 0;i<9;i++)
        {
            printf("uart_buff_ptr[%d] = %x\r\n",i,uart_buff_ptr[i]);
        }
        if(uart_buff[0] == 0x01 && uart_buff[1] == 0x03 && uart_buff[2] == 0x04)        //花卉种类
        {
            data_hum[0] = uart_buff[3];
            data_hum[1] = uart_buff[4];
            data_temp[0] = uart_buff[5];
            data_temp[1] = uart_buff[6];
            data_ph[0] = uart_buff[7];
            data_ph[1] = uart_buff[8];

            HexToAscii(data_hum,datas,sizeof(data_hum));
            hum = hexToDec(datas) / 10.0;
            printf("hum = %f\r\n",hum);

            HexToAscii(data_temp,datas,sizeof(data_temp));
            temperature = hexToDec(datas) / 10.0;
            printf("temp = %f\r\n",temperature);

            HexToAscii(data_ph,datas,sizeof(data_ph));
            ph = hexToDec(datas) / 100.0;
            printf("ph = %f\r\n",ph);

        }
        
        /*        
        if(uart_buff[0] == 0xaa && uart_buff[1] == 0x55 && uart_buff[3] == 0x05)        //花卉种类
        {
            type = uart_buff[2];
            printf("type = %x\r\n",type);
        }
        */
        TaskMsleep(2000);
    }
}

#define UART1_TASK_STACK_SIZE 1024 * 8
#define UART1_TASK_PRIO 26

static void Uart1Entry(void)
{
    osThreadAttr_t attr;
    attr.name = "Uart1Task";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = UART1_TASK_STACK_SIZE; /* 任务大小4096 */
    attr.priority = UART1_TASK_PRIO;
    if (osThreadNew(Uart1Task, NULL, &attr) == NULL) {
        printf("[uart1] Falied to create Uart1Task!\n");
    }
    else{
        printf("[uart1] Successed to create Uart1Task in priority:%d!\n",UART1_TASK_PRIO);
    }
}
APP_FEATURE_INIT(Uart1Entry);